package com.xfsong.demo.aspect;

import com.xfsong.demo.annotation.RateLimit;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class RateLimitAspect {

    private final ConcurrentHashMap<String, Integer> requestCountMap = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, Long> startTimeMap = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @Around("@annotation(com.example.demo.annotation.RateLimit)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        RateLimit rateLimit = method.getAnnotation(RateLimit.class);
        int time = rateLimit.time();
        int count = rateLimit.count();

        HttpServletRequest request = getRequest();
        String key = getKey(request, method);

        long currentTime = System.currentTimeMillis();
        Long startTime = startTimeMap.get(key);
        if (startTime == null || currentTime - startTime > time * 1000) {
            requestCountMap.put(key, 1);
            startTimeMap.put(key, currentTime);
            scheduleCleanup(key, time);
        } else {
            int currentCount = requestCountMap.getOrDefault(key, 0);
            if (currentCount >= count) {
                throw new RuntimeException("访问频率过高，请稍后再试");
            }
            requestCountMap.put(key, currentCount + 1);
        }
        return point.proceed();
    }

    private String getKey(HttpServletRequest request, Method method) {
        String ip = request.getRemoteAddr();
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
        return String.format("%s:%s:%s", ip, className, methodName);
    }

    private HttpServletRequest getRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            throw new RuntimeException("无法获取请求信息", e);
        }
    }

    private void scheduleCleanup(String key, int time) {
        scheduler.schedule(() -> {
            requestCountMap.remove(key);
            startTimeMap.remove(key);
        }, time, TimeUnit.SECONDS);
    }
}